package language.advanced.functional;

import java.util.function.Supplier;
import java.util.stream.Stream;

public class BasicSupplier<T> implements Supplier<T> {
        private Class<T> type;

        public BasicSupplier(Class<T> type) {
            this.type = type;
        }

        @Override
        public T get() {
            try {
                // Assumes type is a public class:因为这个函数返回的是一个对象，所以需要造出一个对象来
                System.out.println("get instance");
                return type.newInstance();
            } catch (InstantiationException |
                    IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }

        // Produce a default Supplier from a type token:
        public static <T> Supplier<T> create(Class<T> type) {
            System.out.println("return create,只执行一次");
            return new BasicSupplier<>(type);
        }


}

class CountedObject {
    private static long counter = 0;
    private final long id = counter++;

    @Override
    public String toString() {
        return "CountedObject " + id;
    }
}

class BasicSupplierDemo {
    public static void main(String[] args) {
        Stream  .generate(BasicSupplier.create(CountedObject.class))
                .limit(5)
                .forEach(System.out::println);
    }
}